package com.czxy.changgou3.com.czxy.changgou3.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.czxy.changgou3.pojo.User;
import com.czxy.utils.SmsUtil;
import com.czxy.vo.BaseResult;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangmengxiang1@itcast.cn
 * @version 1.0
 * @date 2020/4/21
 */
@RestController
@RequestMapping("/sms")
public class SMSController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping
    public BaseResult sendSms(@RequestBody User user){
        long start = System.currentTimeMillis();
        try {
            //发送短信
            //1 生产验证码
            String code = RandomStringUtils.randomNumeric(4);
            //2 并存放到reids中 , key: "sms_register" + 手机号 ， value：验证码 , 1小时
            redisTemplate.opsForValue().set("sms_register"+user.getMobile(),code,1,TimeUnit.HOURS);
            //发送短信
            SendSmsResponse smsResponse = SmsUtil.sendSms(user.getMobile(), user.getUsername(), code, "", "");
            //https://help.aliyun.com/document_detail/55284.html?spm=5176.doc55322.6.557.KvvIJx
            if ("OK".equalsIgnoreCase(smsResponse.getCode())){
                return BaseResult.ok("发送成功");
            }else {
                return BaseResult.error(smsResponse.getMessage());
            }
        } catch (Exception e) {
            long end = System.currentTimeMillis();
            System.out.println(end - start);
            return BaseResult.error("发送失败");
        }
    }

}
